﻿using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;

namespace WindowsFormsApp1
{
	public partial class MainForm : Form
	{
		// 定义一个字典存储文本框和提示语的映射关系
		private Dictionary<TextBox, string> m_mapPlaceholder;
		// 定义提示语
		private string m_strTbxNameTip = "书名";
		private string m_strTbxAuthorTip = "作者";
		private string m_strTbxPressTip = "出版社";
		private string m_strTbxSearchTip = "输入关键字来搜索";
		private BindingList<Book> m_Books;

		public MainForm()
		{
			InitializeComponent();

			// 调用方法加载数据
			LoadBooks();

			// 初始化提示语字典
			m_mapPlaceholder = new Dictionary<TextBox, string>
			{
				{ tbxName, m_strTbxNameTip },
				{ tbxAuthor, m_strTbxAuthorTip},
				{ tbxPress, m_strTbxPressTip },
				{ tbxSearch, m_strTbxSearchTip }
			};

			// 绑定事件
			BindTextboxEvent();
		}

		// 绑定事件
		private void BindTextboxEvent()
		{
			foreach (var textBox in m_mapPlaceholder.Keys)
			{
				textBox.Enter += TextBox_Enter;
				textBox.Leave += TextBox_Leave;
			}
		}

		// 通用的 Enter 事件处理程序
		private void TextBox_Enter(object sender, EventArgs e)
		{
			var textBox = sender as TextBox;
			if (textBox != null && textBox.Text == GetPlaceholderText(textBox))
			{
				textBox.Text = "";
				textBox.ForeColor = Color.Black; // 恢复默认字体颜色
			}
		}

		// 通用的 Leave 事件处理程序
		private void TextBox_Leave(object sender, EventArgs e)
		{
			var textBox = sender as TextBox;
			if (textBox != null && string.IsNullOrWhiteSpace(textBox.Text))
			{
				textBox.Text = GetPlaceholderText(textBox);
				textBox.ForeColor = Color.Gray; // 设置提示语颜色
			}
		}

		// 获取对应文本框的提示语
		private string GetPlaceholderText(TextBox textBox)
		{
			return m_mapPlaceholder.ContainsKey(textBox) ? m_mapPlaceholder[textBox] 
				: string.Empty;
		}

		private void LoadBooks()
		{
			//// 数据库连接字符串
			//string connectionString = "server=localhost;database=bookms;user=root;password=123456;";

			//try
			//{
			//	// 创建连接对象
			//	using (MySqlConnection connection = new MySqlConnection(connectionString))
			//	{
			//		// 打开连接
			//		connection.Open();

			//		// SQL 查询语句
			//		string query = "SELECT id, name, author, press FROM book";

			//		// 创建命令对象
			//		MySqlCommand command = new MySqlCommand(query, connection);

			//		// 执行查询并获取结果
			//		using (MySqlDataReader reader = command.ExecuteReader())
			//		{
			//			// 清空 ListView 的内容
			//			listView1.Items.Clear();

			//			// 遍历查询结果
			//			while (reader.Read())
			//			{
			//				// 获取每一行的数据
			//				string id = reader["id"].ToString();
			//				string name = reader["name"].ToString();
			//				string author = reader["author"].ToString();
			//				string press = reader["press"].ToString();

			//				// 创建 ListViewItem 并添加到 ListView
			//				var item = new ListViewItem(new[] { id, name, author, press });
			//				listView1.Items.Add(item);
			//			}
			//		}
			//	}
			//}
			//catch (Exception ex)
			//{
			//	// 捕获异常并显示错误信息
			//	MessageBox.Show("发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			//}

			m_Books = new BindingList<Book>
			{
				new Book { Id = 1, Name = "红楼梦", Author = "曹雪芹", Press = "人民文学出版社" },
				new Book { Id = 2, Name = "西游记", Author = "昊承恩", Press = "中华书局" },
				new Book { Id = 3, Name = "水浒传", Author = "施耐庵", Press = "人民文学出版社" },
				new Book { Id = 4, Name = "三国演义", Author = "罗贯中", Press = "中华书局" },
				new Book { Id = 5, Name = "百年孤独", Author = "加西亚·马尔克斯", Press = "南海出版社" },
				new Book { Id = 6, Name = "追风筝的人", Author = "卡勒德·胡赛尼", Press = "上海人民出版社" },
				new Book { Id = 7, Name = "小王子", Author = "安托万·德·圣-埃克苏佩里", Press = "译林出版社" },
				new Book { Id = 8, Name = "1984", Author = "乔治·奥威尔", Press = "译林出版社" },
				new Book { Id = 9, Name = "简爱", Author = "夏洛蒂·勃朗特", Press = "人民文学出版社" },
				new Book { Id = 10, Name = "了不起的盖茨比", Author = "F.斯科特·菲茨杰拉德", Press = "上海译文出版社" },
				new Book { Id = 11, Name = "时间简史", Author = "斯蒂芬·威廉·霍金", Press = "湖南科学技术出版社" },
				new Book { Id = 12, Name = "思考，快与慢", Author = "丹尼尔·卡尼曼", Press = "中信出版社" },
				new Book { Id = 13, Name = "活着", Author = "余华", Press = "作家出版社" },
				new Book { Id = 14, Name = "人类简史", Author = "尤瓦尔·赫拉利", Press = "中信出版社" },
			};

			BindSource();
		}

		private void BindSource()
		{
			// 绑定 BindingSource 到 DataGridView
			dataGridView1.DataSource = new BindingSource { DataSource = m_Books };
		}

		// 检查字段是否为空或仅为提示语
		private bool IsFieldEmptyOrPlaceholder(string fieldValue, string placeholder)
		{
			return string.IsNullOrEmpty(fieldValue) || fieldValue == placeholder;
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			string strName = tbxName.Text.Trim();
			string strAuthor = tbxAuthor.Text.Trim();
			string strPress = tbxPress.Text.Trim();

			// 检查是否有字段为空或仅为提示语
			if (IsFieldEmptyOrPlaceholder(strName, m_strTbxNameTip) ||
				IsFieldEmptyOrPlaceholder(strAuthor, m_strTbxAuthorTip) ||
				IsFieldEmptyOrPlaceholder(strPress, m_strTbxPressTip))
			{
				MessageBox.Show("所有字段均为必填项。", "输入错误",
					MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			DialogResult result = MessageBox.Show(
				$"是否要添加这本书\n\n书名: {strName}\n作者: {strAuthor}\n出版社: {strPress}", 
				"添加确认", 
				MessageBoxButtons.YesNo, 
				MessageBoxIcon.Question, 
				MessageBoxDefaultButton.Button1
			);

			if (result == DialogResult.Yes)
			{
				int nNewId = m_Books.Count + 1;
				Book newBook = new Book { Id = nNewId, Name = strName, Author = strAuthor, Press = strPress };
				m_Books.Add(newBook);
				ClearInputFields();
			}
		}

		private void ClearInputFields()
		{
			tbxName.Text = string.Empty;
			tbxAuthor.Text = string.Empty;
			tbxPress.Text = string.Empty;
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			// 确保选中了一行
			if (dataGridView1.SelectedRows.Count <= 0)
			{
				MessageBox.Show("请先选择要更新的图书。", "提示", 
					MessageBoxButtons.OK, MessageBoxIcon.Information);
			}

			// 获取选中的行和对应的图书对象
			DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
			Book selectedBook = selectedRow.DataBoundItem as Book;

			if (selectedBook != null)
			{
				// 获取用户输入的新信息
				string strNewName = IsFieldEmptyOrPlaceholder(tbxName.Text, m_strTbxNameTip) ? selectedBook.Name : tbxName.Text;
				string strNewAuthor = IsFieldEmptyOrPlaceholder(tbxAuthor.Text, m_strTbxAuthorTip) ? selectedBook.Author : tbxAuthor.Text;
				string strNewPress = IsFieldEmptyOrPlaceholder(tbxPress.Text, m_strTbxPressTip) ? selectedBook.Press : tbxPress.Text;

				// 检查是否有任何更改
				if (strNewName == selectedBook.Name &&
					strNewAuthor == selectedBook.Author &&
					strNewPress == selectedBook.Press)
				{
					MessageBox.Show("未检测到任何更改，请修改至少一个字段。", "无更改", MessageBoxButtons.OK, MessageBoxIcon.Warning);
					return;
				}

				// 构造确认信息
				string strDialogContent = $"确认更新图书信息：\n\n" +
									$"旧信息：\n" +
									$"名称：{selectedBook.Name}\n" +
									$"作者：{selectedBook.Author}\n" +
									$"出版社：{selectedBook.Press}\n\n" +
									$"新信息：\n" +
									$"名称：{strNewName}\n" +
									$"作者：{strNewAuthor}\n" +
									$"出版社：{strNewPress}";

				// 显示确认对话框
				DialogResult result = MessageBox.Show(strDialogContent, "确认更新", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

				if (result == DialogResult.OK)
				{
					// 更新数据库（如果需要）
					// using (var connection = new MySqlConnection(App.ConnectionString))
					// {
					//     connection.Open();
					//     using (var command = new MySqlCommand("UPDATE book SET name=@name, author=@auth, press=@press WHERE id=@id", connection))
					//     {
					//         command.Parameters.AddWithValue("@id", selectedBook.id);
					//         command.Parameters.AddWithValue("@name", newName);
					//         command.Parameters.AddWithValue("@auth", newAuthor);
					//         command.Parameters.AddWithValue("@press", newPress);
					//         command.ExecuteNonQuery();
					//     }
					// }

					// 更新内存中的对象
					selectedBook.Name = strNewName;
					selectedBook.Author = strNewAuthor;
					selectedBook.Press = strNewPress;

					// 刷新 DataGridView

					// 清空输入框
					ClearInputFields();
				}
			}
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			// 检查 DataGridView 控件当前选定的行是否有效。
			if (dataGridView1.SelectedRows.Count <= 0)
			{
				// 如果没有选中任何行，显示提示信息
				MessageBox.Show("请选择要删除的图书。", "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}

			// 获取选中的行和对应的图书对象
			DataGridViewRow selectedRow = dataGridView1.SelectedRows[0];
			Book selectedBook = selectedRow.DataBoundItem as Book;

			if (selectedBook != null)
			{
				// 构造删除确认信息
				string strDialogContent = $"是否要删除这本书？\n\n" +
									$"ID: {selectedBook.Id}\n" +
									$"书名: {selectedBook.Name}\n" +
									$"作者: {selectedBook.Author}\n" +
									$"出版社: {selectedBook.Press}";

				// 显示确认对话框
				DialogResult result = MessageBox.Show(strDialogContent, "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

				if (result == DialogResult.OK)
				{
					// 删除数据库记录（如果需要）
					// using (var connection = new MySqlConnection(App.ConnectionString))
					// {
					//     connection.Open();
					//     using (var command = new MySqlCommand("DELETE FROM book WHERE id=@id", connection))
					//     {
					//         command.Parameters.AddWithValue("@id", selectedBook.Id);
					//         command.ExecuteNonQuery();
					//     }
					// }

					// 从内存中移除该书籍
					m_Books.Remove(selectedBook);
				}
			}
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			BindSource();
		}

		private void btnSearch_Click(object sender, EventArgs e)
		{
			// 获取用户输入的关键字并去除首尾空格，转换为小写
			string strKeyword = tbxSearch.Text.Trim().ToLower();

			if (string.IsNullOrEmpty(strKeyword))
			{
				// 如果搜索关键字为空，则显示所有书籍
				BindSource();
			}
			else
			{
				// 创建一个临时列表用于存储过滤后的书籍
				List<Book> filteredBooks = new List<Book>();

				// 遍历所有书籍并检查是否符合条件
				foreach (Book book in m_Books)
				{
					if (book.Name.ToLower().Contains(strKeyword) ||
						book.Author.ToLower().Contains(strKeyword) ||
						book.Press.ToLower().Contains(strKeyword))
					{
						filteredBooks.Add(book);
					}
				}

				// 绑定过滤后的数据到 DataGridView
				dataGridView1.DataSource = null; // 清除现有数据
				dataGridView1.DataSource = filteredBooks;
			}
		}

		private void tableLayoutClick(object sender, MouseEventArgs e)
		{
			// 将焦点设置到窗体本身
			this.ActiveControl = null;
		}
	}
}
